/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

package scenic.toolkit.db;

import java.util.Vector;

import scenic.toolkit.db.event.ArrayInsertEvent;
import scenic.toolkit.db.event.ArrayRemoveEvent;
import scenic.toolkit.db.event.ArrayWriteEvent;
import scenic.toolkit.db.event.ChangeEvent;

public abstract class SyncVector<T> extends Vector<T> implements NodeListener {
	private NodeArray source;
	
	public SyncVector(NodeArray source) {
		this.source = source;
		
		for(int i = 0; i < source.getLength(); i++)
			add(i, createObject(i, source.get(i)));
		endUpdate();
		source.addListener(this);
	}
	
	public abstract T createObject(int index, Object sourceNode);
	
	public abstract void removeObject(int index, Object object);
	
	public void endUpdate() {	
	}
	
	public void changed(ChangeEvent event) {
		if(event.getNode() != source)
			return;
		if(event instanceof ArrayInsertEvent) {
			ArrayInsertEvent ie = (ArrayInsertEvent)event;
			
			for(int i = ie.getPosition(); i < ie.getPosition() + ie.getLength(); i++)
				add(i, createObject(i, source.get(i)));
			endUpdate();
		}
		else if(event instanceof ArrayWriteEvent) {
			ArrayWriteEvent ie = (ArrayWriteEvent)event;
			
			for(int i = ie.getPosition(); i < ie.getPosition() + ie.getLength(); i++) {
				removeObject(i, get(i));
				set(i, createObject(i, source.get(i)));
			}
			endUpdate();
		}
		else if(event instanceof ArrayRemoveEvent) {
			ArrayRemoveEvent ie = (ArrayRemoveEvent)event;
			
			for(int i = ie.getPosition(); i < ie.getPosition() + ie.getLength(); i++) {
				removeObject(i, remove(ie.getPosition()));
			}
			endUpdate();
		}
	}
}
